package com.winphone.uvam.shiro;

import com.winphone.uvam.common.Constant;
import com.winphone.uvam.entity.SysUser;
import com.winphone.uvam.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhou
 * @Description:
 * @Date:Create in 2017/12/13
 * @Modified By:
 */

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService userService;

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===== 认证=====");
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        SysUser user = userService.getSysUserInfoByUserName(username);
        if (user == null){
            throw new AccountException("帐号或密码不正确！");
        }else if (user.getUserState().equals(Constant.SYSUSER_STATE_2)){
            throw new LockedAccountException("此帐号已经设置为禁止登录！");
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());//放入shiro.调用CredentialsMatcher检验密码
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        SysUser user=(SysUser) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户

        List<String> permissions=new ArrayList<>();
//        Set<Role> roles = user.getRoles();
//        if(roles.size()>0) {
//            for(Role role : roles) {
//                Set<Module> modules = role.getModules();
//                if(modules.size()>0) {
//                    for(Module module : modules) {
//                        permissions.add(module.getMname());
//                    }
//                }
//            }
//        }
//        if (user.getUsername().equals("admin")){
            permissions.add("user:add");
            permissions.add("user:edit");
            permissions.add("user:delete");
//        }

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);//将权限放入shiro中.

        return info;
    }

}
